package com.jcl.recruit.core.utils;

import com.jcl.core.constants.RedisConstant;
import com.jcl.core.model.RedisChannelAccount;
import com.jcl.recruit.channel.model.ChannelNet;
import com.jcl.recruit.core.config.SystemConfig;
import com.jcl.recruit.core.config.redis.RedisCache;

/**
 * @ClassName RedisCacheUtils
 * @Description TODO
 * @Author yyliu
 * @Date 2018/11/20 9:21
 * @Version 1.0
 **/
public class RedisCacheUtils {

    public static void addChanelAccount(ChannelNet channelNet) {
        ChanelAccountCache.addChanelAccount(channelNet);
    }

    public static String getWechatAccessToken() {
        return WechatCache.getAccessToken(SystemConfig.getSystemWechatAppid());
    }

    public static void setWechatAccessToken(String accessToken) {
        WechatCache.setAccessToken(SystemConfig.getSystemWechatAppid(), accessToken);
    }

    public static String getWechatTicket() {
        return WechatCache.getTicket(SystemConfig.getSystemWechatAppid());
    }

    public static void setWechatTicket(String ticket) {
        WechatCache.setTicket(SystemConfig.getSystemWechatAppid(), ticket);
    }

}

class WechatCache {

    public static String getAccessToken(String appId) {
        String key = RedisConstant.KEY_WECHAT_ACCESS_TOKEN + appId;
        return RedisCache.getStr(key);
    }

    public static void setAccessToken(String appId, String accessToken) {
        String key = RedisConstant.KEY_WECHAT_ACCESS_TOKEN + appId;
        RedisCache.setex(key, accessToken, RedisConstant.WECHAT_TIMEOUT);
    }

    public static String getTicket(String appId) {
        String key = RedisConstant.KEY_WECHAT_TICKET + appId;
        return RedisCache.getStr(key);
    }

    public static void setTicket(String appId, String ticket) {
        String key = RedisConstant.KEY_WECHAT_TICKET + appId;
        RedisCache.setex(key, ticket, RedisConstant.WECHAT_TIMEOUT);
    }
}

class ChanelAccountCache {

    public static void addChanelAccount(ChannelNet channelNet) {
        String key = RedisConstant.KEY_CHANNEL_ACCOUNT + RedisConstant.REDIS_SPLIT_KEY + channelNet.getChannelType();
        RedisChannelAccount account = new RedisChannelAccount();
        account.setAccount(channelNet.getAccountName());
        account.setUsername(channelNet.getAccount());
        account.setPassword(channelNet.getPassword());
        account.setCorpCode(channelNet.getCorpCode());
        account.setSiteCode(channelNet.getChannelType());
        RedisCache.addMap(key, channelNet.getCorpCode(), account);
        // 添加队列
        addChanelAccountCorpCode(channelNet.getChannelType(), channelNet.getCorpCode());
    }

    private static void addChanelAccountCorpCode(String channelType, String corpCode) {
        String key = RedisConstant.KEY_CHANNEL_ACCOUNT_CORP
                + RedisConstant.REDIS_SPLIT_KEY + channelType;
        RedisCache.rpush(key, corpCode);
    }
}